import { _decorator, Component, Node, Color, CCInteger, Sprite, director, tween } from 'cc';
import { AudioController } from './AudioController';
const { ccclass, property } = _decorator;
import { GameData } from './GameData';
const gameData = GameData.getInstance()

@ccclass('Choose')
export class Choose extends Component {
    @property(Node)
    selectNode = null

    @property(Node)
    coolDownNode = null

    @property(Node)
    cardNode = null
    // 是否有足够的钱解锁
    unlock = false

    // 是否冷却了
    isCoolDown = true

    isSelect = false

    @property(CCInteger)
    price = 100 // 价格

    @property(CCInteger)
    type = 1 // 类型

    start() {
        this.node.on(Node.EventType.TOUCH_START, this.select, this);
        director.getScene().on('drop-plant', function(){
            // 植物被放置成功
            if(+gameData.selectType === +this.type){
                
                this.audioController = director.getScene().getChildByName('Canvas').getComponent(AudioController);
                this.audioController.playOneShot('growPlantClip')

                gameData.setSunEnergy(-this.price)
                this.selectNode.active = false;
                this.isSelect = false
                gameData.setSelectType(-1);
                this.isCoolDown = false
                this.coolDownNode.active = true
                const height = this.coolDownNode.height;
                tween(this.coolDownNode)
                    .to(2, { height: 0 })
                    .call(() => {
                        console.log('动画完成');
                        // 冷却时间2s后还原
                        this.coolDownNode.active = false;
                        this.coolDownNode.height = height;
                        this.isCoolDown = true
                    })
                    .start();
            }
        }, this)
    }

    update(deltaTime: number) {
        if(gameData.totalSunEnergy >= this.price){
            this.unlock = true
            this.node.getChildByName('choose').getComponent(Sprite).color = new Color(255, 255, 255)
        }else{
            this.unlock = false
            this.node.getChildByName('choose').getComponent(Sprite).color = new Color(73, 69, 69)
        }
    }
    select(){
        if(this.isCoolDown && this.unlock){
            let allItem = this.node.parent.children
            // 取消其他的选中
            allItem.forEach((node) => {
                let component = node.getComponent(Choose)
                component.isSelect = false
                component.selectNode.active = false;
            });
            this.isSelect = true
            this.selectNode.active = true
            gameData.setSelectType(this.type)
        }
    }
}

